package com.cnbot.dchttpsdk.helper;


import java.io.IOException;

import okhttp3.MediaType;
import okhttp3.ResponseBody;
import okio.Buffer;
import okio.BufferedSource;
import okio.ForwardingSource;
import okio.Okio;
import okio.Source;

/**
 * Copyright (c) 2016-a  Hunan Cnbot Co., Ltd. All Rights Reserved.
 *
 * @descriptoin 带progress的请求
 * @FileName: ProgressResponseBody.java
 * @author: dc
 * @date: 2019/1/19 14:12
 * @version: 1.0
 */

public class ProgressResponseBody extends ResponseBody {

    private final ResponseBody             responseBody;
    private final DownFileProgressListener listener;
    private       BufferedSource           bufferedSource;

    public ProgressResponseBody(ResponseBody responseBody, DownFileProgressListener listener) {
        this.responseBody = responseBody;
        this.listener = listener;
    }


    @Override
    public MediaType contentType() {
        return responseBody.contentType();
    }

    @Override
    public long contentLength() {
        return responseBody.contentLength();
    }

    @Override
    public BufferedSource source() {
        if (null == bufferedSource) {
            bufferedSource = Okio.buffer(source(responseBody.source()));
        }
        return bufferedSource;
    }

    public Source source(Source source) {
        ForwardingSource forwardingSource = new ForwardingSource(source) {
            long totalBytesRead = 0L;

            @Override
            public long read(Buffer sink, long byteCount) throws IOException {
                long bytesRead = super.read(sink, byteCount);
                // read() returns the number of bytes read, or -1 if this source is exhausted.
                totalBytesRead += bytesRead != -1 ? bytesRead : 0;

                if (null != listener) {
                    listener.onProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1);
                }
                return bytesRead;
            }
        };

        return forwardingSource;
    }
}
